import { ecs } from "db://oops-framework/libs/ecs/ECS";
import {
  _decorator,
  Component,
  CCInteger,
  Node,
  sys,
  Input,
  input,
  EventTouch,
  EventMouse,
  Vec3,
} from "cc";

const { menu, property, ccclass } = _decorator;

const v3_0 = new Vec3();

/**
 * 触摸全屏
 */
@ccclass("CHARACTER.BearingController")
@menu("demo/character-controller/BearingController")
@ecs.register("BearingController")
export class BearingControllerComp extends Component {
  @property({ type: CCInteger, tooltip: "比例因素" })
  invocableFactor = 1000;

  @property({ type: Node, tooltip: "全屏节点" })
  fullScreen: Node = null!;

  protected _bind: OmitThisParameter<() => void> | undefined;

  protected _bind2: any;

  isBrowser = sys.isBrowser;

  protected onEnable() {
    if (this.isBrowser) {
      this._bind = this.onFullScreenChange.bind(this);
      document.addEventListener("fullscreenchange", this._bind, false);
    }
    this.fullScreen.children[0].on(
      Input.EventType.TOUCH_START,
      this.onTouchStart,
      this
    );
  }

  protected onFullScreenChange() {
    this.fullScreen.active = !this.fullScreen.active;
    if (this.fullScreen.active && this.isBrowser) {
      document.removeEventListener("mousemove", this._bind2, false);
    } else if (this.fullScreen.active && !this.isBrowser) {
      input.off(Input.EventType.MOUSE_MOVE, this.onMouseMove, this);
    } else if (this.isBrowser) {
      this._bind2 = this.onMouseMove.bind(this);
      document.addEventListener("mousemove", this._bind2, false);
    } else {
      input.on(Input.EventType.MOUSE_MOVE, this.onMouseMove, this);
    }
  }

  /**
   * 全屏
   * @param touch 触屏事件
   * @protected
   */
  protected onTouchStart(touch: EventTouch) {
    let element = document.body;
    // 允许你异步地请求将鼠标指针锁定在指定元素上,兼任Mozilla Firefox和WebKit 内核
    // @ts-ignore
    element.requestPointerLock =
      element.requestPointerLock ||
      element["mozRequestPointerLock"] ||
      element["webkitRequestPointerLock"];
    element.requestPointerLock();

    // @ts-ignore
    element.requestFullscreen =
      element.requestFullscreen ||
      element[`mozRequestFullScreen`] ||
      element[`webkitRequestFullscreen`];
    element.requestFullscreen().then((r) => { });
  }

  /**
   * 鼠标移动
   * @param event 鼠标事件
   * @protected
   */
  protected onMouseMove(event: EventMouse | MouseEvent) {
    let deltaX = 0;
    if (this.isBrowser) {
      // @ts-ignore
      deltaX =
        event.movementX ||
        event[`mozMovementX`] ||
        event[`webkitMovementX`] ||
        0;
    } else {
      deltaX = (event as EventMouse).getDeltaX();
    }
    const eluerY = this.node.eulerAngles.y;
    v3_0.set(
      0,
      eluerY + (-deltaX * Math.abs(deltaX)) / this.invocableFactor,
      0
    );
    this.node.eulerAngles = v3_0;
  }
}
